<!-- 项目 -->
<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="keywords">
          <el-input
            v-model="queryParams.keywords"
            placeholder="字典名称/编码"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-[10px]">
        <el-button type="success" icon="plus" @click="handleAddClick()">新增</el-button>
        <el-button type="danger" :disabled="ids.length === 0" icon="delete" @click="handleDelete()">
          删除
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="项目名称" prop="projectName" />
        <el-table-column label="项目编号" prop="projectCode" />
        <el-table-column label="项目文件地址" prop="filePath" />
        <el-table-column label="项目地址" prop="webUrl" />
        <el-table-column label="项目所属模块" prop="module" />
        <el-table-column label="docker的序号" prop="dockerIdx" />
        <el-table-column label="相关的静态资源地址" prop="staticPath" />
        <el-table-column label="端口号" prop="port" />
        <el-table-column label="备注" prop="remark" />
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button type="primary" link size="small" @click.stop="handleOpenDictData(scope.row)">
              <template #icon>
                <Collection />
              </template>
              详情数据
            </el-button>

            <el-button
              type="primary"
              link
              size="small"
              icon="edit"
              @click.stop="handleEditClick(scope.row.id, scope.row.name)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              icon="delete"
              @click.stop="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!--字典弹窗-->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="computedRules" label-width="100px">
        <el-card shadow="never">
          <el-form-item label="页面名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入页面名称" />
          </el-form-item>

          <el-form-item label="弹窗名称" prop="modalName">
            <el-input v-model="formData.modalName" placeholder="请输入项目名称" />
          </el-form-item>

          <el-form-item label="列信息1" prop="filePath">
            <el-table :data="tableData" style="width: 100%">
              <el-table-column
                v-for="item in columns"
                :key="item.prop"
                :prop="item.prop"
                :label="item.label"
              >
                <template #default="{ row, column }">
                  <el-input
                    v-if="editableCell === row.id && editableColumn === column.property"
                    :ref="`input_${row.id}_${column.property}`"
                    v-model="row[column.property]"
                    @blur="handleInputBlur"
                    @keyup.enter="handleInputEnter"
                  />
                  <span v-else>{{ row[column.property] }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>

          <el-form-item label="项目地址" prop="webUrl">
            <el-input v-model="formData.webUrl" placeholder="请输入项目地址" />
          </el-form-item>

          <el-form-item label="项目所属模块" prop="module">
            <el-input v-model="formData.module" placeholder="请输入项目所属模块" />
          </el-form-item>

          <el-form-item label="docker的序号" prop="dockerIdx">
            <el-input v-model="formData.dockerIdx" placeholder="请输入docker的序号" />
          </el-form-item>

          <el-form-item label="相关的静态资源地址" prop="staticPath">
            <el-input v-model="formData.staticPath" placeholder="请输入相关的静态资源地址" />
          </el-form-item>

          <el-form-item label="端口号" prop="port">
            <el-input v-model="formData.port" placeholder="请输入端口号" />
          </el-form-item>

          <el-form-item label="排序">
            <el-input-number v-model="formData.sort" controls-position="right" />
          </el-form-item>

          <el-form-item label="备注">
            <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
          </el-form-item>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmitClick">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "project",
  inherititems: false,
});

import DictAPI, { DictPageQuery, DictPageVO, DictForm } from "@/api/system/dict";
import ProjectAPI, {
  remoteMovicePageQuery,
  remoteMovicePageVO,
  remoteMoviceForm,
} from "@/api/emo/project";

import router from "@/router";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<DictPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const tableData = ref<DictPageVO[]>();
const columns = ref([
  { label: "列名", prop: "lname" },
  { label: "列参数名", prop: "lcsname" },
  { label: "是否可新增", prop: "isAdd" },
  { label: "表单类型", prop: "bdType" },
  // ... more columns
]);
const editableCell = ref(null);
const editableColumn = ref(null);

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<any>({});

const handleInputBlur = (event) => {
  editableCell.value = null;
  editableColumn.value = null;
};

const handleInputEnter = (event) => {
  const input = event.target;
  const cellId = input.id.split("_")[1];
  const columnProp = input.id.split("_")[2];
  editableCell.value = cellId;
  editableColumn.value = columnProp;
};

const computedRules = computed(() => {
  const rules: Partial<Record<string, any>> = {
    name: [{ required: true, message: "请输入字典名称", trigger: "blur" }],
    dictCode: [{ required: true, message: "请输入字典编码", trigger: "blur" }],
  };
  return rules;
});

// 查询
function handleQuery() {
  loading.value = true;
  ProjectAPI.getPage(queryParams)
    .then((data) => {
      tableData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

// 行选择
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 新增字典
function handleAddClick() {
  dialog.visible = true;
  dialog.title = "新增远程电影";
}

/**
 * 编辑字典
 *
 * @param id 字典ID
 */
function handleEditClick(id: number, name: string) {
  dialog.visible = true;
  dialog.title = "修改字典";
  DictAPI.getFormData(id).then((data) => {
    Object.assign(formData, data);
  });
}

function downloadTextFile(filename, text) {
  // 创建一个Blob实例，里面包含要下载的内容
  const blob = new Blob([text], { type: "text/plain;charset=utf-8" });
  // 创建一个指向该Blob的URL
  const url = URL.createObjectURL(blob);
  // 创建一个a标签
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", filename);
  document.body.appendChild(link);
  // 触发下载
  link.click();
  // 清理
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

// 提交字典表单
function handleSubmitClick() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        ProjectAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        downloadTextFile("example.txt", "Hello, World!");
        // ProjectAPI.add(formData)
        //   .then(() => {
        //     ElMessage.success("新增成功");
        //     handleCloseDialog();
        //     handleQuery();
        //   })
        //   .finally(() => (loading.value = false));
        // 生成代码
      }
    }
  });
}

// 关闭字典弹窗
function handleCloseDialog() {
  dialog.visible = false;

  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
}
/**
 * 删除字典
 *
 * @param id 字典ID
 */
function handleDelete(id?: number) {
  const attrGroupIds = [id || ids.value].join(",");
  if (!attrGroupIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      ProjectAPI.deleteByIds(attrGroupIds).then(() => {
        ElMessage.success("删除成功");
        handleResetQuery();
      });
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开字典数据
function handleOpenDictData(row: DictPageVO) {
  router.push({
    path: "/emo/remoteMoviceData",
    query: { parentId: row.id },
  });

  /*  router.push({
    name: "DictData",
    params: { dictCode: row.dictCode, title: "【" + row.name + "】字典数据" },
  }); */
}

onMounted(() => {
  handleQuery();
});
</script>
